package com.zhiyou.aifeng.smart_machine

import android.os.Bundle
import android.widget.ImageView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.jeremyliao.liveeventbus.utils.observe
import com.zhiyou.aifeng.common.base.gone
import com.zhiyou.aifeng.common.base.visible
import com.zhiyou.aifeng.common.helper.formatDecimal
import com.zhiyou.aifeng.common.helper.get
import com.zhiyou.aifeng.common.helper.getString
import com.zhiyou.aifeng.common.helper.getTimeString
import com.zhiyou.aifeng.common_ui.base.*
import com.zhiyou.aifeng.common_ui.model.BaseUrl
import com.zhiyou.aifeng.common_ui.model.CommonData
import com.zhiyou.aifeng.common_ui.utils.bindLifeCycle
import com.zhiyou.aifeng.common_ui.utils.showHintDialog
import com.zhiyou.aifeng.common_ui.utils.subscribeByFinally
import com.zhiyou.aifeng.utils.setEmptyIcon
import com.zhiyou.aifeng.viewmodel.MatterViewModel
import kotlinx.android.synthetic.main.layout_empty.*
import kotlinx.android.synthetic.main.layout_list.*
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

class MatterActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_matter)
        initTitle("订单列表", divider = false)

        swipe_refresh.isRefreshing = true
        getData(pageNum)
    }

    override fun getViewModel() = get<MatterViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        initList()

        observe("matterList") { value ->
            if (mList.any { (it as CommonData).njsjid == value }) {
                val index = mList.indexOfFirst { (it as CommonData).njsjid == value }
                mList.removeAt(index)
                mAdapter.notifyItemRemoved(index)
                empty_view.apply { if (mList.isEmpty()) visible() else gone() }
            }
        }
    }

    private fun initList() {
        empty_img.setEmptyIcon()
        empty_hint.text = "暂无相关订单信息！"
        swipe_refresh.refresh { getData(1) }
        recycle_list.apply {
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
            loadLinear(baseContext, swipe_refresh) {
                if (!isLoadingMore) {
                    isLoadingMore = true
                    getData(pageNum)
                }
            }

            mAdapter = SlimAdapter.create()
                .register<CommonData>(R.layout.item_matter_list) { data, injector ->

                    val index = mList.indexOf(data)

                    injector.text(R.id.item_matter_title, data.work_type_name)
                        .text(
                            R.id.item_matter_price,
                            "亩数：${data.area.formatDecimal()}亩    价格：${data.price.formatDecimal()}元/亩"
                        )
                        .text(
                            R.id.item_matter_time,
                            "时间：${data.preset_date.getTimeString("yyyy-MM-dd HH:mm")}（预计）"
                        )
                        .text(
                            R.id.item_matter_adress,
                            data.region_addr.replace(" ", "") + data.address
                        )
                        .with<ImageView>(R.id.item_matter_img) {
                            it.loadImage(data.icon)
                        }
                        .clicked(R.id.item_matter_get) {
                            if (getString("auth") != "2") {
                                toast("您还未通过实名认证，暂无法操作！")
                                return@clicked
                            }

                            getMatter(data.njsjid, index)
                        }
                        .clicked(R.id.item_matter) {
                            startActivity<MatterDetailActivity>("orderId" to data.njsjid)
                        }

                }
                .attachTo(this)
        }
    }

    private fun getMatter(dataId: String, index: Int) {
        showHintDialog(
            title = "确认接单",
            hint = "是否确认立即接单？"
        ) {
            getViewModel().request(
                requestUrl = BaseUrl.workGet,
                params = *arrayOf(
                    "uid" to getString("userId"),
                    "njsjid" to dataId
                ),
                onResult = {
                    toast("确认接单成功！")
                    mList.removeAt(index)
                    mAdapter.notifyItemRemoved(index)
                    empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                }
            )
        }
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().getMatterList(index, getString("userId"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mList.apply {
                        if (index == 1) {
                            clear()
                            pageNum = index
                        }
                        addItems(it)
                        if (it.count() > 0) pageNum++
                    }

                    mAdapter.updateData(mList)
                },
                onFinally = {
                    swipe_refresh.isRefreshing = false
                    isLoadingMore = false
                    empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                }
            )
    }

}